#include "xllp_i2c.h"
#include "xllp_defs.h"

typedef enum {
    XLLP_RESOURCE_I2C = 0,
    XLLP_RESOURCE_MFPR,          // MFP registers
    XLLP_RESOURCE_MFPR_RM,       // MFP resource manager
    XLLP_RESOURCE_ID_COUNT,
    XLLP_RESOURCE_CLK_EN
} XLLP_PROTECTED_RESOURCES_ID_T; // more IDs might be added

XLLP_STATUS_T XllpLock(XLLP_PROTECTED_RESOURCES_ID_T Xllp_RegisterID);
XLLP_STATUS_T XllpUnlock(XLLP_PROTECTED_RESOURCES_ID_T Xllp_LockID);
int OS_I2CMasterWriteData(XLLP_UINT8_T slaveAddr, const XLLP_UINT8_T * bytesBuf, int bytesCount);
int OS_I2CMasterReadData(XLLP_UINT8_T slaveAddr, XLLP_UINT8_T * bytesBuf, int bufLen);
int printf(const char *fmt, ...);

//0:success
//other : wrong
int InitI2c(void)
{
	int ret;

	P_XLLP_I2C_T pReg = (P_XLLP_I2C_T)0x40301680;
	P_XLLP_VUINT32_T	pMfpRegBase = (P_XLLP_VUINT32_T)0x40E10000;
	P_XLLP_MFP_RM_DB_ID_T pMfpRMDb = (P_XLLP_MFP_RM_DB_ID_T) 0x5c012000;
	ret = (int)XllpI2cInit(pReg, pMfpRegBase, pMfpRMDb, 0);

	return ret;
}

//0:OK
//other: wrong
int I2cWriteByte(unsigned char slaveAddr, unsigned char reg, unsigned char val)
{
    unsigned char buf[2];
    int status;

    buf[0] = reg;
    buf[1] = val;

    //printf("\nI2cWriteByte() -- YX");
    XllpLock(XLLP_RESOURCE_I2C);
    status = OS_I2CMasterWriteData(slaveAddr, buf, 2);
    XllpUnlock(XLLP_RESOURCE_I2C);
    return status;
}

//0:success
//other:fail
int I2cReadByte(unsigned char slaveAddr, unsigned char reg, unsigned char * pval)
{
    int status;
    unsigned char  buf[1];

    buf[0] = reg;
    XllpLock(XLLP_RESOURCE_I2C);
    status = OS_I2CMasterWriteData(slaveAddr, buf, 1);
    if (status != XLLP_STATUS_SUCCESS) {
        XllpUnlock(XLLP_RESOURCE_I2C);
        return status;
    }

    status = OS_I2CMasterReadData(slaveAddr, pval, 1);
    XllpUnlock(XLLP_RESOURCE_I2C);
    return status;
}
